package io.plus.utils.lock;

import lombok.extern.slf4j.Slf4j;

import java.util.Set;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;

@Slf4j
public class ReadWriteLockSet<T> extends ReadWriteLockObject<Set<T>> {
    private static final long serialVersionUID = -2305909960649321346L;

    public ReadWriteLockSet(Set<T> set) {
        super(set);
    }

    public ReadWriteLockSet(Set<T> set, ReentrantReadWriteLock lock) {
        super(set, lock);
    }

    public boolean add(T t) {
        WriteLock writeLock = this.getWriteLock();
        writeLock.lock();
        try {
            Set<T> set = this.getObject();
            return set.add(t);
        } catch (Throwable e) {
            log.error(e.getMessage(), e);
        } finally {
            writeLock.unlock();
        }
        return false;
    }

    public void clear() {
        WriteLock writeLock = this.getWriteLock();
        writeLock.lock();
        try {
            Set<T> set = this.getObject();
            set.clear();
        } catch (Throwable e) {
            log.error(e.getMessage(), e);
        } finally {
            writeLock.unlock();
        }
    }

    public boolean remove(T t) {
        WriteLock writeLock = this.getWriteLock();
        writeLock.lock();
        try {
            Set<T> set = this.getObject();
            return set.remove(t);
        } catch (Throwable e) {
            log.error(e.getMessage(), e);
        } finally {
            writeLock.unlock();
        }
        return false;
    }

    public int size() {
        ReadLock readLock = this.getReadLock();
        readLock.lock();
        try {
            Set<T> set = this.getObject();
            return set.size();
        } finally {
            readLock.unlock();
        }
    }
}
